

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'tieBa'
});
connection.connect();

var datas={"code":0,"data":'',"msg":''};
exports.login=function(user,callback){
 var sql="SELECT * from user_info where name='"+user.name+"' and password='"+user.password+"'";
  connection.query(sql,function (err, result) {
    if(err){
      datas.msg=err.message;
      callback(datas)
    }else{
        localStorage.setItem("isLogin","1");
        localStorage.setItem("user",JSON.stringify(result[0]));
      callback(datas)
    }
  });
};


exports.saveComment=function(comment,callBack){
    var user=localStorage.getItem("user");
    var user=JSON.parse(user);
    var sql="INSERT INTO `tiebas`(`pid`, `content`, `userName`, `userId`) VALUES (?, ?, ?, ?);";
    var  addSqlParams = [comment.id,comment.content,user.name, user.id];
    connection.query(sql,addSqlParams,function (err,results) {
        callBack(null,results);
    })
};

exports.commentList=function(callBack){
    connection.query('SELECT * from tiebas where pid=0', function (error, results, fields) {
        if (error) throw error;
        callBack(results);
    });
};
exports.comment = function (id, callback) {
    connection.query("SELECT * from tiebas where id="+id, function (error, results, fields){
        localStorage.setItem("comment",JSON.stringify(results[0]));
    });
    connection.query("SELECT * from tiebas where pid="+id, function (error, results, fields){
        callback(results)
    });

};


/**
 * 添加保存
 * @param  {Object}   user  对象
 * @param  {Function} callback 回调函数
 */
exports.save = function (user, callback) {
  var sql="INSERT INTO user_info( `name`, `password`,phone) VALUES (?,?,?)";
  var  addSqlParams = [user.name, user.password,user.phone];
  connection.query(sql,addSqlParams,function (err,results) {
    callback(null);
  })
}


/**
 * 删除
 */
exports.deleteById = function (id, callback) {
  var sql="DELETE from tiebas where id="+id;
  connection.query(sql,function (err,result) {
    callback(null);
  })
}
